<template>
  <div>
    <el-input v-model="searchQuery" placeholder="请输入学生姓名进行查询" style="width: 200px; margin-right: 10px;" />
    <el-button type="primary" @click="handleSearch">查询</el-button>
    <el-button @click="handleReset">重置</el-button>
    <el-button type="primary" @click="handleAdd"> 添加学生</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="学生姓名" width="180" />
      <el-table-column prop="age" label="年龄" width="180" />
      <el-table-column prop="grade" label="年级" width="180" />
    </el-table>

    <el-dialog v-model="dialogVisble" title="添加学生">
      <el-form ref="addFormRef" :model="addForm"
               :rules="rules" label-width="80px" class="ruleForm"
               status-icon>
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="addForm.name"/>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="addForm.age"/>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="addForm.grade"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisble=false">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm()">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { onMounted, reactive, ref } from "vue";
import axios from "axios";

const tableData = ref([]);
const searchQuery = ref(""); // 查询输入框的绑定变量

const getList = async (query = "") => {
  try {
    let res;
    if (query) {
      res = await axios.get(`http://localhost:8000/adminapi/students?name=${query}`);
    } else {
      res = await axios.get('http://localhost:8000/adminapi/students');
    }
    tableData.value = res.data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

const handleAdd = () => {
  dialogVisble.value = true;
}
const dialogVisble = ref(false);
const addFormRef = ref();
const addForm = reactive({
  name: "",
  age: "",
  grade: ""
});
const rules = reactive({
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
  ],
  grade: [
    { required: true, message: '请输入年级', trigger: 'blur' },
  ],
})
const handleAddConfirm = () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      dialogVisble.value = false;
      await axios.post('http://localhost:8000/adminapi/students', addForm);
      await getList();
      addForm.name = "";
      addForm.age = "";
      addForm.grade = "";
    }
  })
}

onMounted(() => {
  getList();
})

// 查询
const handleSearch = () => {
  getList(searchQuery.value);
}

// 重置
const handleReset = () => {
  searchQuery.value = "";
  getList();
}
</script>

